
import React, { useReducer, useState } from 'react';
import { DndProvider, useDrag, useDrop,DragSource, DropTarget } from 'react-dnd';
import {HTML5Backend} from 'react-dnd-html5-backend';

const ITEM_TYPES = {
  DRAGGABLE_ITEM: 'draggable_item',
};

const DraggableItem = ({ id, text }) => {
  const [{ isDragging }, drag] = useDrag({
    type: ITEM_TYPES.DRAGGABLE_ITEM,
    item: { id,text },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  return (
    <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
      {text}
    </div>
  );
};

const DropZone = ({ onDrop,content }) => {
  const [{ canDrop, isOver }, drop] = useDrop({
    accept: ITEM_TYPES.DRAGGABLE_ITEM,
    drop: (item) => onDrop(item),
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  });

  let backgroundColor = '';
  if (isOver && canDrop) {
    backgroundColor = 'lightgreen';
  } else if (isOver && !canDrop) {
    backgroundColor = 'pink';
  }
  return (
    <div ref={drop} style={{ padding: '20px', backgroundColor }}>
      {content ? content :'Drop here!  '} 
    </div>
  );
};


function App() {
  const [items, setItems] = useState();
  const [state,dispatch] = useReducer((state,action)=>({...state,...action}),{
      dimList:[
        { id: 1, text: '维度 1' },
        { id: 2, text: '维度 2' },
        { id: 3, text: '维度 3' },
        { id: 4, text: '维度 4' },
        // ...
      ],
      rowDimList:[],
      colDimList:[],
  })
  const handleDrop = (droppedItem,type) => {
    state.dimList = state.dimList.filter((item) => item.id !== droppedItem.id);
    console.log('droppedItem',droppedItem)
    type === 'rowDim' ? state.rowDimList.push(droppedItem) : state.colDimList.push(droppedItem)
    console.log('state',state)
    dispatch({...state});
  };
  const {dimList,rowDimList,colDimList} = state
  let rowDimCom = rowDimList.map(item => {
      let {id,text} = item
      return <div key = {id}>{text}</div>
  })
  let colDimCom = colDimList.map(item => {
      let {id,text} = item
      return <div key = {id}>{text}</div>
  })
  return (
    <DndProvider backend={HTML5Backend}>
      <div >
        <div>
          <h2>维度</h2>
          <ul>
            {dimList.map((item) => (
              <DraggableItem key={item.id} id={item.id} text={item.text} />
            ))}
          </ul>
        </div>
        <div>
          <h2>行维度</h2>
          <DropZone onDrop={(item)=>{handleDrop(item,'rowDim')}} content = {rowDimCom}/>
          {/* 添加更多 DropZone 组件 */}
        </div>
        <div>
          <h2>列维度</h2>
          <DropZone onDrop={(item)=>{handleDrop(item,'colDim')}} content={colDimCom}/>
          {/* 添加更多 DropZone 组件 */}
        </div>
      </div>
    </DndProvider>
  );
}

export default App;
